package com.pan.download5.driver;

import com.pan.download5.config.FindLine;
import com.pan.download5.config.entity.LineInfo;
import com.pan.download5.config.TaskConfig;
import com.pan.download5.factory.DirectoryFactory;
import com.pan.download5.factory.PageFactory;
import com.pan.download5.factory.builder.AbstractPageDirectoryFactory;
import com.pan.download5.factory.builder.FactoryEntity;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class FastDriver implements Driver, FindLine, TaskConfig {


    public void run(){
        run(this.getTargetCrawlerUrl(),this.getDefaultThreadCount());
    }

    public void run(int threadCount){
        run(this.getTargetCrawlerUrl(),threadCount);
    }

    public void run(String url){
        run(url,this.getDefaultThreadCount());
    }

    @Override
    public void run(String url, int threadCount) {
        LineInfo lineInfo = byUrl(url);
        String builderClassName = lineInfo.getConfigType().getFactory();

        DirectoryFactory directoryFactory;
        PageFactory pageFactory;
        try {
            Class<? extends AbstractPageDirectoryFactory> abstractPageDirectoryFactoryClass
                    = (Class<? extends AbstractPageDirectoryFactory>) Class.forName(builderClassName);
            Constructor<? extends AbstractPageDirectoryFactory> constructor =
                    abstractPageDirectoryFactoryClass.getConstructor();
            AbstractPageDirectoryFactory pageDirectoryFactory = constructor.newInstance();
            FactoryEntity factoryEntity = pageDirectoryFactory.createFactory(lineInfo);
            directoryFactory = factoryEntity.getDirectoryFactory();
            pageFactory = factoryEntity.getPageFactory();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

        Driver driver = new Basic2Driver(directoryFactory, pageFactory);
        driver.run(url, threadCount);
    }


}
